package com.econage.eccm.test.base.webdatasource.web;

import com.econage.eccm.test.base.mybatis.support.MybatisWebContext;
import com.google.common.util.concurrent.RateLimiter;

import javax.servlet.*;
import java.io.IOException;
import java.sql.SQLException;
import java.util.concurrent.TimeUnit;

public class AppDataSourceFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        DbTransaction.checkAppDataSource();//连接池
        MybatisWebContext.checkSqlSessionTemplate();//mybatis环境
    }

    //在新的规范中，filter可以拦截include请求，添加isNestedReq、isRootReq用于判断是否是嵌套请求
    private ThreadLocal<Boolean> isNestedReq = new ThreadLocal<Boolean>(){
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean isRootReq = false;
        try {
            if(!isNestedReq.get()){
                isRootReq = true;
                DbTransaction.register4Access();
                isNestedReq.set(true);
            }
            chain.doFilter(request, response);
        }finally{
            if(isRootReq){
                try{
                    MybatisWebContext.close();
                }finally{
                    try {
                        DbTransaction.closeForce();
                    }finally{
                        isNestedReq.remove();
                    }
                }
            }
        }
    }

    @Override
    public void destroy() {

    }
}
